package com.cropdoctor.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cropdoctor.common.CustomException;
import com.cropdoctor.common.Result;
import com.cropdoctor.mapper.SysUserMapper;
import com.cropdoctor.mapper.SysUserRoleRelationMapper;
import com.cropdoctor.mapper.VegeFruTableMapper;
import com.cropdoctor.model.constants.PageParams;
import com.cropdoctor.model.constants.PageResult;
import com.cropdoctor.model.po.SysUserPo;
import com.cropdoctor.model.po.SysUserRoleRelationPo;
import com.cropdoctor.model.po.VegeFrutablePo;
import com.cropdoctor.model.vo.UserVO;
import com.cropdoctor.service.AdminService;
import com.cropdoctor.util.AliOssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.UUID;

@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    VegeFruTableMapper vegeFruTableMapper;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    AliOssUtil ossUtil;

    @Autowired
    SysUserMapper sysUserMapper;

    @Autowired
    SysUserRoleRelationMapper sysUserRoleRelationMapper;

    @Override
    public Result<String> adminAddVegAndFruTable(VegeFrutablePo vegeFrutablePo,MultipartFile file) {
        String url = null;
        try {
            //获取原始的文件名
            String originalFilename = file.getOriginalFilename();
            //在oss中存储名字就是UUID + 文件的后缀名
            String objectName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
            url = ossUtil.upload(file.getBytes(), "remark/"+objectName);
        } catch (IOException e) {
            e.printStackTrace();
            throw new CustomException("上传图片失败!");
        }

        vegeFrutablePo.setUrl(url);

        //将数据插入到果蔬表中
        int result = vegeFruTableMapper.insert(vegeFrutablePo);
        //若数据插入失败，抛出CustomException异常
        if (result <= 0) throw new CustomException("数据插入失败！");
        redisTemplate.opsForValue().set("table",null);//重置缓存数据
        return Result.success("数据插入成功！");
    }

    @Override
    public Result<String> deleteById(long idTable) {
        //将数据从果蔬表中删除
        int result = vegeFruTableMapper.deleteById(idTable);

        //若数据删除失败，抛出CustomException异常
        if (result <= 0) throw new CustomException("数据删除失败！");
        redisTemplate.opsForValue().set("table",null);//重置缓存数据
        return Result.success("数据删除成功！");
    }

    @Override
    public Result<String> updateById(VegeFrutablePo vegeFrutablePo) {
        //将数据更新到果蔬表中
        int result = vegeFruTableMapper.updateById(vegeFrutablePo);

        //若数据更新失败，抛出CustomException异常
        if (result <= 0) throw new CustomException("数据更新失败！");
        redisTemplate.opsForValue().set("table",null);//重置缓存数据
        return Result.success("数据更新成功！");
    }

    @Override
    public Result<String> addAdmin(SysUserPo sysUserPo, MultipartFile img) {
        String filename = img.getOriginalFilename();
        byte[] bytes = null;
        File tempFile = null;
        try {
            tempFile = File.createTempFile("oss", "temp");
            String absolutePath = tempFile.getAbsolutePath();//临时文件路径
            bytes = img.getBytes();
            img.transferTo(tempFile);
        } catch (IOException e) {
            e.printStackTrace();
            throw new CustomException("创建临时文件失败!");
        }finally {
            if(tempFile != null) tempFile.delete();//程序退出时删除临时文件
        }
        String url = null;
        //获取原始的文件名
        String originalFilename = tempFile.getName();
        //在oss中存储名字就是UUID + 文件的后缀名
        String objectName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
        url = ossUtil.upload(bytes, "account/"+objectName);

        //进一步封装sysUserPo
        //创建人id
        Integer adminId = Integer.valueOf(((HashMap<String, Object>) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).get("userid").toString());
        sysUserPo.setAvatarUrl(url);
        sysUserPo.setEnabled(1);

        //将数据插入到用户表中
        int result1 = sysUserMapper.insert(sysUserPo);
        //若插入失败，则抛出CustomException异常
        if (result1 <= 0) throw new CustomException("用户表数据插入失败");

        //封装SysUserRoleRelationPo，用户默认权限为admin
        Integer idUser = sysUserPo.getId();
        SysUserRoleRelationPo sysUserRoleRelationPo = new SysUserRoleRelationPo();
        sysUserRoleRelationPo.setUserId(idUser);
        sysUserRoleRelationPo.setRoleId(1);

        //将sysUserRoleRelationPo插入到用户角色关系表中，若插入失败，则抛出CustomException异常
        sysUserRoleRelationMapper.insert(sysUserRoleRelationPo);
        if (result1 <= 0) throw new CustomException("用户角色关系表数据插入失败");
        return Result.success("管理员账号添加成功！");
    }

    @Override
    public Result<String> changeUserStatus(Integer idUser,String status) {
        LambdaUpdateWrapper<SysUserPo> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(SysUserPo::getId,idUser).set(SysUserPo::getEnabled,status);
        int result = sysUserMapper.update(null, wrapper);
        return result > 0 ? Result.success("更新成功!") : Result.error("更新失败!");
    }

    @Override
    public Result<String> resetPassword(Integer idUser) {
        //先将对应用户的具体信息查出来
        SysUserPo sysUserPo = sysUserMapper.selectById(idUser);
        //若查询失败，则抛出CustomException异常
        if (sysUserPo == null) throw new CustomException("用户不存在！");
        //将用户密码重置为123
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        sysUserPo.setPassword(bCryptPasswordEncoder.encode("123"));
        //更新状态
        int result = sysUserMapper.updateById(sysUserPo);
        //若更新失败，则抛出CustomException异常
        if (result <= 0) throw new CustomException("重置密码失败，请重试！");
        return Result.success("重置密码成功！");
    }

    @Override
    public Result<PageResult<UserVO>> getAllUser(PageParams pageParams, String account) {
        LambdaQueryWrapper<SysUserPo> wrapper = new LambdaQueryWrapper<>();
        if(!"".equals(account)) wrapper.eq(SysUserPo::getAccount,account);
        Page<SysUserPo> poPage = new Page<>(pageParams.getPageNo(), pageParams.getPageSize());
        Page<UserVO> pageResult = sysUserMapper.selectWithRole(poPage,wrapper);
        PageResult<UserVO> courseBasePageResult = new PageResult<>(pageResult.getRecords(),pageResult.getTotal()
                ,pageParams.getPageNo(),pageParams.getPageSize());
        return Result.success(courseBasePageResult);
    }

    @Override
    public Result<SysUserPo> getUser(Integer idUser) {
        SysUserPo sysUserPo = sysUserMapper.selectById(idUser);

        if (sysUserPo == null) throw new CustomException("该用户不存在！");

        return Result.success(sysUserPo);
    }

    @Override
    public Result<String> changeRole(Long userId, int roleId) {
        LambdaUpdateWrapper<SysUserRoleRelationPo> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(SysUserRoleRelationPo::getUserId,userId).set(SysUserRoleRelationPo::getRoleId,roleId);
        int result = sysUserRoleRelationMapper.update(null, wrapper);
        return result > 0 ? Result.success("修改失败!") : Result.error("修改成功!");
    }
}
